//
//  STComposeBlurView.m
//  OCVVeibo
//
//  Created by leergou on 16/9/3.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

#import "STComposeBlurView.h"
#import "STComposeButtonModel.h"
#import "STComposeButton.h"
#import "STComposeController.h"
#import <pop/POP.h>

@interface STComposeBlurView ()

// 记录控制器
@property (nonatomic,strong) UIViewController *target;
// 背景图片
@property (nonatomic,strong) UIImageView *bgImageView;
// logo图
@property (nonatomic,strong) UIImageView *logoImageView;

// 按钮信息数组
@property (nonatomic,strong) NSArray <STComposeButtonModel *> *buttonInfo;
// 按钮数组
@property (nonatomic,strong) NSMutableArray <STComposeButton *> *buttonArray;

@end

@implementation STComposeBlurView


#pragma mark - 界面跳转入口 -
- (void)showWithTarget:(UIViewController *)target{
    [target.view addSubview:self];
    self.target = target;
    
    // 弹出按钮
    [self setupButtonAnimation:YES];
    
}

#pragma mark - 构造方法 -
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
        
        [self setupUI];
    }
    return self;
}

#pragma mark - setupUI -
-(void)setupUI{
    // 1.添加子控件
    [self addSubview:self.bgImageView];
    [self addSubview:self.logoImageView];
    [self addChildButtons];
    
    // 2.添加约束
    [self.bgImageView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
    [self.logoImageView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.top.equalTo(self).offset(100);
    }];
    
    // 3.添加毛玻璃效果 -- 这种添加磨玻璃效果，实际在原来背景图片的上方，覆盖了一层模糊视图
//    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
//    
//    [self addSubview:effectView];
//    [effectView makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self);
//    }];
    
    // 4.添加毛玻璃效果 - 用分类，这样少了一层视图，只有处理为磨玻璃后的背景
}

#pragma mark - 按钮点击事件 -

- (void)buttonClick:(STComposeButton *)sender{
    
    NSLog(@"点击了");
    
    [UIView animateWithDuration:0.25 animations:^{
        
        // 遍历数组，点击的按钮放大，其他缩小
        for (STComposeButton *button in self.buttonArray) {
            
            button.alpha = 0.2;
            
            if (button == sender) {
                button.transform = CGAffineTransformMakeScale(2, 2);
            } else {
                button.transform = CGAffineTransformMakeScale(0.2, 0.2);
            }
            
        }
        
    } completion:^(BOOL finished) {
        
        // 动画结束后
        [UIView animateWithDuration:0.25 animations:^{
            
            // ，遍历数组，回复按钮大小
            for (STComposeButton *button in self.buttonArray) {
                
                button.alpha = 1;
                button.transform = CGAffineTransformIdentity;
            }
            
        } completion:^(BOOL finished) {
            
            // 回复大小后，控制器跳转
            NSString *vcName = sender.buttonModel.nextvc;
            /*
             自定义类进行动态生成的时候，要在类名前加上项目名称，格式为： 项目名.类名
             */
            #warning - 注意 OC版，不用拼接项目名称
            // 获取项目名称
            //NSString *projectName = [NSBundle mainBundle].infoDictionary[@"CFBundleExecutable"];
            
            // 拼接控制器名称
            Class clazz = NSClassFromString(vcName);
            
            // 创建控制器
            UIViewController *tempVc = [[clazz alloc] init];
            
            if (![tempVc isKindOfClass:[STComposeController class]]) {
                return;
            }
            
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tempVc];
            
            [self.target presentViewController:nav animated:YES completion:^{
                [self removeFromSuperview];
            }];
        }];
    }];
    
    
}

#pragma mark - 按钮动画 -
- (void)setupButtonAnimation:(BOOL)isUp{
    
    CGFloat margin = isUp ? -300 : 300;
    
    // 遍历存放按钮的数组
    for (STComposeButton *button in self.buttonArray) {
        // 计算当前按钮在数组中的下表
        NSInteger index = [self.buttonArray indexOfObject:button];
        // 计算按钮动画开始时间
        CGFloat startTime = isUp ? index * 0.025 :  (self.buttonArray.count - index) * 0.025;
        
        // 开始动画
        POPSpringAnimation *sprintAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
        
        CGRect rect = CGRectMake(button.frame.origin.x, button.frame.origin.y + margin, button.frame.size.width, button.frame.size.height);
        
        sprintAnimation.toValue = [NSValue valueWithCGRect:rect];
        sprintAnimation.beginTime = CACurrentMediaTime() + startTime;
        sprintAnimation.springBounciness = 10.0f;
        sprintAnimation.springSpeed = 8;
        [button pop_addAnimation:sprintAnimation forKey:nil];
    }
}

#pragma mark - addChildButtons -
- (void)addChildButtons{
    
    // 读取按钮信息到数组
    self.buttonInfo = [self getBttonInfo];
    
    // 设置按钮属性
    CGFloat buttonWidth = 80;
    CGFloat buttonHeight = 110;
    
    // 总列数
    NSInteger columns = 3;
    
    // 按钮间距
    CGFloat margin = (SCREEN_WIDTH - columns * buttonWidth) / 4;

    // 遍历按钮信息数组，创建按钮
    for (STComposeButtonModel * model in self.buttonInfo) {
        
        // 计算 列索引和 行索引
        NSInteger index = [self.buttonInfo indexOfObject:model];
        
        NSInteger rowIndex = index / columns;
        NSInteger columnIndex = index % columns;
        
//        STComposeButton *button = [[STComposeButton alloc] initWithTitle:model.title norImg:model.icon target:self action:@selector(buttonClick:)];
        
        STComposeButton *button = [STComposeButton buttonWithType:UIButtonTypeCustom];
        
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        button.buttonModel = self.buttonInfo[index];

        button.frame = CGRectMake((columnIndex + 1) * margin + columnIndex * buttonWidth , (rowIndex + 1) * margin + rowIndex * buttonHeight + SCREEN_HEIGHT, buttonWidth, buttonHeight);
        
        // 添加到 父view
        [self addSubview:button];
        
        // 添加按钮到数组
        [self.buttonArray addObject:button];

    }
}


#pragma mark - 读取按钮信息 - 
// 返回一个数组（数组中存放按钮信息模型）
- (NSArray<STComposeButtonModel *> *)getBttonInfo{
    
    // 读取按钮信息文件
    // 文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"compose" ofType:@"plist"];
    // 读取文件内容到数组
    NSArray *tempArray = [NSArray arrayWithContentsOfFile:path];
    // 可变数组
    NSMutableArray *mutable = [NSMutableArray array];
    // 遍历临时数组
    for (NSDictionary *dict in tempArray) {
        // 字典转模型
        STComposeButtonModel *model = [STComposeButtonModel modelWithDict:dict];
        // 添加到可变数组
        [mutable addObject:model];
    }
    return mutable.copy;
}

#pragma mark - lazy load -
- (UIImageView *)logoImageView{
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] initWithImageName:@"compose_slogan"];
    }
    return _logoImageView;
}

- (UIImageView *)bgImageView{
    if (!_bgImageView) {
        
        // 截屏并制作磨玻璃效果
        _bgImageView = [[UIImageView alloc] initWithImage:[[UIImage getScreenShot] applyLightEffect]];
    }
    return _bgImageView;
}

- (NSMutableArray<STComposeButton *> *)buttonArray{
    if (!_buttonArray) {
        _buttonArray = [NSMutableArray array];
    }
    
    return _buttonArray;
}

#pragma mark - 点击屏幕取消按钮 -
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    
    [self setupButtonAnimation:NO];
    
//        [self removeFromSuperview];
    
    
    //    // 倒叙遍历存放按钮的数组
    //
    //    [self.buttonArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(STComposeButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //
    //        POPSpringAnimation *sprintAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    //
    //        CGRect rect = CGRectMake(obj.frame.origin.x, obj.frame.origin.y + 300, obj.frame.size.width, obj.frame.size.height);
    //
    //        sprintAnimation.toValue = [NSValue valueWithCGRect:rect];
    //        sprintAnimation.beginTime = CACurrentMediaTime() + (self.buttonArray.count - idx) * 0.05;
    //        sprintAnimation.springBounciness = 10.0f;
    //        sprintAnimation.springSpeed = 8;
    //        [obj pop_addAnimation:sprintAnimation forKey:nil];
    //        
    //    }];
    //
    
}

@end
